//
//  IflyMSCManager.m
//  YueYueSpecailCarDriver
//
//  Created by 李亚军 on 17/3/7.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "IflyMSCManager.h"
#import "PcmPlayer.h"
#import "iflyMSC/iflyMSC.h"
#import <AVFoundation/AVFoundation.h>
#import "TTSConfig.h"



typedef NS_OPTIONS(NSInteger, SynthesizeType) {
    NomalType           = 5,//普通合成
    UriType             = 6, //uri合成
};


@interface IflyMSCManager ()<IFlySpeechSynthesizerDelegate>

@property (nonatomic, strong) PcmPlayer *audioPlayer; // 播放器,继承AVAudioPlayerDelegate


@property (nonatomic, assign) SynthesizeType synType; // 合成的类型

@property (nonatomic, strong) NSString *uriPath; // 语音合成存放路径



@property(nonatomic , assign) BOOL isCanceled; // 是否取消

@property (nonatomic, assign) BOOL hasError; // 是否有错误信息

@end

static IflyMSCManager *iflyMSCManager = nil;
@implementation IflyMSCManager
// 初始化单利
static dispatch_once_t onceToken;
+ (IflyMSCManager *)shareManager {
    
//    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        iflyMSCManager = [IflyMSCManager new];
        //     使用-(void)synthesize:(NSString *)text toUri:(NSString*)uri接口时， uri 需设置为保存音频的完整路径
        //     若uri设为nil,则默认的音频保存在library/cache下
        NSString *prePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        //uri合成路径设置
        iflyMSCManager.uriPath = [NSString stringWithFormat:@"%@/%@",prePath,@"uri.pcm"];
        //pcm播放器初始化
        iflyMSCManager.audioPlayer = [[PcmPlayer alloc] init];
        
    });
    return iflyMSCManager;
}

/**
 开始将文字合成语音
 */
+ (IflyMSCManager *)startSyntheticSpeechWithText:(NSString *)text {
    
    // 初始化单利
//    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        iflyMSCManager = [IflyMSCManager new];
        //     使用-(void)synthesize:(NSString *)text toUri:(NSString*)uri接口时， uri 需设置为保存音频的完整路径
        //     若uri设为nil,则默认的音频保存在library/cache下
        NSString *prePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        //uri合成路径设置
        iflyMSCManager.uriPath = [NSString stringWithFormat:@"%@/%@",prePath,@"uri.pcm"];
        //pcm播放器初始化
        iflyMSCManager.audioPlayer = [[PcmPlayer alloc] init];
        
    });
    
    [iflyMSCManager initSynthesizer];
    
    [iflyMSCManager registerNotification];
    
    if (![text isEqualToString:@""] && text != nil) {
        
        [iflyMSCManager startSynthesisWithText:text];
    }
    
    return iflyMSCManager;
}

/**
 为导航提供语音
 */
+ (IflyMSCManager *)startSyntheticSpeechForNaviWithText:(NSString *)text {
    
    dispatch_once(&onceToken, ^{
        
        iflyMSCManager = [IflyMSCManager new];
        //     使用-(void)synthesize:(NSString *)text toUri:(NSString*)uri接口时， uri 需设置为保存音频的完整路径
        //     若uri设为nil,则默认的音频保存在library/cache下
        NSString *prePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        //uri合成路径设置
        iflyMSCManager.uriPath = [NSString stringWithFormat:@"%@/%@",prePath,@"uri.pcm"];
        //pcm播放器初始化
        iflyMSCManager.audioPlayer = [[PcmPlayer alloc] init];
        
    });
    
    [iflyMSCManager initSynthesizer];
    
    [iflyMSCManager registerNotification];
    
    if (![text isEqualToString:@""] && text != nil) {
        if (iflyMSCManager.state != Playing) {
            
            [iflyMSCManager startSynthesisForNaviWithText:text];
        }
        
    }
    
    return iflyMSCManager;
}


/**
 配置默认属性
 */
- (void)initSynthesizer
{
    TTSConfig *instance = [TTSConfig sharedInstance];
    if (instance == nil) {
        return;
    }
    
    //合成服务单例
    if (self.iFlySpeechSynthesizer == nil) {
        self.iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    }
    
    self.iFlySpeechSynthesizer.delegate = self;
    
    /*
    // 这里使用默认,下面的参数不配置
    //设置语速1-100
    [self.iFlySpeechSynthesizer setParameter:instance.speed forKey:[IFlySpeechConstant SPEED]];
    
    //设置音量1-100
    [self.iFlySpeechSynthesizer setParameter:instance.volume forKey:[IFlySpeechConstant VOLUME]];
    
    //设置音调1-100
    [self.iFlySpeechSynthesizer setParameter:instance.pitch forKey:[IFlySpeechConstant PITCH]];
    
    //设置采样率
    [self.iFlySpeechSynthesizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
    
    //设置发音人
    [self.iFlySpeechSynthesizer setParameter:instance.vcnName forKey:[IFlySpeechConstant VOICE_NAME]];
    
    //设置文本编码格式
    [self.iFlySpeechSynthesizer setParameter:@"unicode" forKey:[IFlySpeechConstant TEXT_ENCODING]];
    */
    
//    NSDictionary* languageDic=@{@"Guli":@"text_uighur", //维语
//                                @"XiaoYun":@"text_vietnam",//越南语
//                                @"Abha":@"text_hindi",//印地语
//                                @"Gabriela":@"text_spanish",//西班牙语
//                                @"Allabent":@"text_russian",//俄语
//                                @"Mariane":@"text_french"};//法语
//    
//    NSString* textNameKey=[languageDic valueForKey:instance.vcnName];
//    NSString* textSample=nil;
//    
//    if(textNameKey && [textNameKey length]>0){
//        textSample=NSLocalizedStringFromTable(textNameKey, @"tts/tts", nil);
//    }else{
//        textSample=NSLocalizedStringFromTable(@"text_chinese", @"tts/tts", nil);
//    }
//    [_textView setText:textSample];
    
}


/**
 注册通知
 */
- (void)registerNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pausePlay:) name:IFlySpeech_PausePlayback object:nil]; // 暂停播放
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelSynthesis:) name:IFlySpeech_CompositeCancel object:nil];
}


/**
 暂停播放
 */
- (void)pausePlay:(NSNotification *)aNotification {
    
    [self.audioPlayer stop];
}


/**
 取消合成
 */
- (void)cancelSynthesis:(NSNotification *)aNotictication {

    [self.iFlySpeechSynthesizer stopSpeaking];
}

/**
 开始合成
 */
- (void)startSynthesisWithText:(NSString *)text {
    
    if ([text isEqualToString:@""]) {

        return;
    }
    
    if (self.audioPlayer != nil && self.audioPlayer.isPlaying == YES) {
        [self.audioPlayer stop];
    }
    
    self.synType = UriType;
    
    self.hasError = NO;
    
    [NSThread sleepForTimeInterval:0.05];
    
    self.isCanceled = NO;
    
    self.iFlySpeechSynthesizer.delegate = self;
    
    [self.iFlySpeechSynthesizer synthesize:text toUri:self.uriPath];
    if (self.iFlySpeechSynthesizer.isSpeaking) {
        self.state = Playing;
    }
}

/**
 开始合成for 导航
 */
- (void)startSynthesisForNaviWithText:(NSString *)text {
    
    if ([text isEqualToString:@""]) {
        
        return;
    }
    
    if (self.audioPlayer.isPlaying == YES) {
        
        return;
    }
    
    if (self.audioPlayer != nil && self.audioPlayer.isPlaying == YES) {
        [self.audioPlayer stop];
    }
    
    self.synType = UriType;
    
    self.hasError = NO;
    
    [NSThread sleepForTimeInterval:0.05];
    
    self.isCanceled = NO;
    
    self.iFlySpeechSynthesizer.delegate = self;
    
    [self.iFlySpeechSynthesizer synthesize:text toUri:self.uriPath];
    if (self.iFlySpeechSynthesizer.isSpeaking) {
        self.state = Playing;
    }
}

#pragma mark - 合成回调 IFlySpeechSynthesizerDelegate

/**
 开始合成回调
 注：
 对通用合成方式有效，
 对uri合成无效
 ****/
- (void)onSpeakBegin
{
    
    self.isCanceled = NO;
    if (self.state != Playing) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_StartSynthesis object:nil];
    }
    self.state = Playing;
}



/**
 缓冲进度回调
 
 progress 缓冲进度
 msg 附加信息
 注：
 对通用合成方式有效，
 对uri合成无效
 ****/
- (void)onBufferProgress:(int)progress message:(NSString *)msg
{
    
    
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    [info setValue:@(progress) forKey:@"progress"];
    [info setValue:msg forKey:@"msg"];
    [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_CacheSchedule object:info];
}




/**
 播放进度回调
 
 progress 缓冲进度
 
 注：
 对通用合成方式有效，
 对uri合成无效
 ****/
- (void) onSpeakProgress:(int)progress beginPos:(int)beginPos endPos:(int)endPos
{
    
    
    
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    [info setValue:@(progress) forKey:@"progress"];
    [info setValue:@(beginPos) forKey:@"beginPos"];
    [info setValue:@(endPos) forKey:@"endPos"];
    [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_PlaybackProgress object:info];
}


/**
 合成暂停回调
 注：
 对通用合成方式有效，
 对uri合成无效
 ****/
- (void)onSpeakPaused
{
    
    self.state = Paused;
    [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_PausePlayback object:nil];
}


/**
 合成结束（完成）回调
 
 对uri合成添加播放的功能
 ****/
- (void)onCompleted:(IFlySpeechError *) error
{
    
    
    if (error.errorCode != 0) {
        
//        [_popUpView showText:[NSString stringWithFormat:@"错误码:%d",error.errorCode]];
        [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_ErrorCode object:error]; // 发送错误码
        return;
    }
//    NSString *text ;
    if (self.isCanceled) {
//        text = @"合成已取消";
        [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_CompositeCancel object:nil];
    }else if (error.errorCode == 0) {
//        text = @"合成结束";
        [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_SynthesisCompleted object:nil];
    }else {
//        text = [NSString stringWithFormat:@"发生错误：%d %@",error.errorCode,error.errorDesc];
        self.hasError = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_ErrorCode object:nil];
    }
    
    self.state = NotStart;
    
    if (self.synType == UriType) {//Uri合成类型 , 合成完成后播放
        
        NSFileManager *fm = [NSFileManager defaultManager];
        if ([fm fileExistsAtPath:self.uriPath]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:IFlySpeech_StartPlay object:nil];
            [self playUriAudio];//播放合成的音频
        }
    }
}

#pragma mark - 播放合成完成后的音频
- (void)playUriAudio
{
    TTSConfig *instance = [TTSConfig sharedInstance];
    NSError *error = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
    self.audioPlayer = [[PcmPlayer alloc] initWithFilePath:self.uriPath sampleRate:[instance.sampleRate integerValue]];
    [self.audioPlayer play];

}

- (void)dealloc {
    
    NSLog(@"播报页面销毁了");
}

@end
